<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        /* 基础样式设置 */
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        
        /* 游戏容器样式 */
        .game-container {
            position: relative;
            margin: 20px auto;
        }
        
        /* 游戏画布样式 */
        #game-canvas {
            background-color: #e0e0e0;
            border: 2px solid #333;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        
        /* 控制面板样式 */
        .control-panel {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        /* 按钮通用样式 */
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        /* 分数显示区域 */
        .score-panel {
            display: flex;
            justify-content: space-between;
            width: 100%;
            max-width: 400px;
            margin-bottom: 15px;
            font-size: 18px;
            font-weight: bold;
        }
        
        /* 难度选择器样式 */
        .difficulty-selector {
            margin-top: 15px;
        }
        
        .difficulty-selector label {
            margin-right: 10px;
        }
        
        /* 游戏结束弹窗 */
        .game-over {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
            display: none;
            z-index: 10;
        }
        
        .game-over h2 {
            color: #e74c3c;
            margin-top: 0;
        }
        
        /* 网格线样式 */
        .grid-line {
            position: absolute;
            background-color: rgba(0, 0, 0, 0.05);
        }
    </style>
</head>
<body>
    <h1>贪吃蛇游戏</h1>
    
    <div class="score-panel">
        <div>当前得分: <span id="current-score">0</span></div>
        <div>最高得分: <span id="high-score">0</span></div>
    </div>
    
    <div class="game-container">
        <canvas id="game-canvas" width="400" height="400"></canvas>
        
        <div class="game-over" id="game-over">
            <h2>游戏结束!</h2>
            <p>你的得分: <span id="final-score">0</span></p>
            <p id="score-comparison"></p>
            <button id="restart-button">重新开始</button>
        </div>
    </div>
    
    <div class="difficulty-selector">
        <label>难度:</label>
        <select id="difficulty">
            <option value="easy">简单</option>
            <option value="medium" selected>普通</option>
            <option value="hard">困难</option>
        </select>
    </div>
    
    <div class="control-panel">
        <button id="start-button">开始游戏</button>
        <button id="pause-button" disabled>暂停</button>
        <button id="reset-button">重置</button>
    </div>

    <script>
        // 游戏主逻辑
        document.addEventListener('DOMContentLoaded', () => {
            // 获取DOM元素
            const canvas = document.getElementById('game-canvas');
            const ctx = canvas.getContext('2d');
            const currentScoreElement = document.getElementById('current-score');
            const highScoreElement = document.getElementById('high-score');
            const finalScoreElement = document.getElementById('final-score');
            const scoreComparisonElement = document.getElementById('score-comparison');
            const gameOverElement = document.getElementById('game-over');
            const startButton = document.getElementById('start-button');
            const pauseButton = document.getElementById('pause-button');
            const resetButton = document.getElementById('reset-button');
            const restartButton = document.getElementById('restart-button');  // 修正这里：documentreset -> document
            const difficultySelector = document.getElementById('difficulty');
            
            // 游戏配置
            const config = {
                gridSize: 20, // 网格数量
                cellSize: canvas.width / 20, // 每个网格的像素大小
                initialSpeed: 150, // 初始速度（毫秒）
                speedIncrease: 0.05, // 每次吃食物速度增加5%
                easySpeed: 200,
                mediumSpeed: 150,
                hardSpeed: 100,
                easySpeedIncrease: 0.03,
                mediumSpeedIncrease: 0.05,
                hardSpeedIncrease: 0.08
            };
            
            // 游戏状态
            let snake = [];
            let food = {};
            let direction = 'right';
            let nextDirection = 'right';
            let gameInterval;
            let isPaused = false;
            let isGameOver = false;
            let score = 0;
            let highScore = localStorage.getItem('snakeHighScore') || 0;
            let currentSpeed = config.mediumSpeed;
            let speedIncrease = config.mediumSpeedIncrease;
            
            // 初始化游戏
            function initGame() {
                // 重置游戏状态
                snake = [
                    {x: 2, y: 0},
                    {x: 1, y: 0},
                    {x: 0, y: 0}
                ];
                direction = 'right';
                nextDirection = 'right';
                score = 0;
                isGameOver = false;
                isPaused = false;
                gameOverElement.style.display = 'none';
                currentScoreElement.textContent = '0';
                
                // 根据难度设置速度
                updateDifficulty();
                
                // 生成第一个食物
                generateFood();
                
                // 绘制游戏
                drawGame();
            }
            
            // 更新难度设置
            function updateDifficulty() {
                const difficulty = difficultySelector.value;
                switch(difficulty) {
                    case 'easy':
                        currentSpeed = config.easySpeed;
                        speedIncrease = config.easySpeedIncrease;
                        break;
                    case 'medium':
                        currentSpeed = config.mediumSpeed;
                        speedIncrease = config.mediumSpeedIncrease;
                        break;
                    case 'hard':
                        currentSpeed = config.hardSpeed;
                        speedIncrease = config.hardSpeedIncrease;
                        break;
                }
                
                // 如果游戏正在进行，更新速度
                if (gameInterval) {
                    clearInterval(gameInterval);
                    if (!isPaused && !isGameOver) {
                        gameInterval = setInterval(gameLoop, currentSpeed);
                    }
                }
            }
            
            // 生成食物
            function generateFood() {
                let validPosition = false;
                let foodX, foodY;
                
                // 确保食物不会生成在蛇身上
                while (!validPosition) {
                    foodX = Math.floor(Math.random() * config.gridSize);
                    foodY = Math.floor(Math.random() * config.gridSize);
                    
                    validPosition = true;
                    for (let segment of snake) {
                        if (segment.x === foodX && segment.y === foodY) {
                            validPosition = false;
                            break;
                        }
                    }
                }
                
                food = {x: foodX, y: foodY};
            }
            
            // 游戏主循环
            function gameLoop() {
                if (isPaused || isGameOver) return;
                
                // 更新蛇的位置
                moveSnake();
                
                // 检查碰撞
                checkCollisions();
                
                // 检查是否吃到食物
                checkFood();
                
                // 绘制游戏
                drawGame();
            }
            
            // 移动蛇
            function moveSnake() {
                // 更新方向
                direction = nextDirection;
                
                // 获取蛇头
                const head = {...snake[0]};
                
                // 根据方向移动蛇头
                switch(direction) {
                    case 'up':
                        head.y -= 1;
                        break;
                    case 'down':
                        head.y += 1;
                        break;
                    case 'left':
                        head.x -= 1;
                        break;
                    case 'right':
                        head.x += 1;
                        break;
                }
                
                // 将新头部添加到蛇身
                snake.unshift(head);
                
                // 移除蛇尾（除非吃到食物）
                if (!foodEaten) {
                    snake.pop();
                } else {
                    foodEaten = false;
                }
            }
            
            // 检查碰撞
            function checkCollisions() {
                const head = snake[0];
                
                // 检查撞墙
                if (head.x < 0 || head.x >= config.gridSize || 
                    head.y < 0 || head.y >= config.gridSize) {
                    gameOver();
                    return;
                }
                
                // 检查撞到自己
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        gameOver();
                        return;
                    }
                }
            }
            
            let foodEaten = false;
            
            // 检查是否吃到食物
            function checkFood() {
                const head = snake[0];
                
                if (head.x === food.x && head.y === food.y) {
                    // 增加分数
                    score += 10;
                    currentScoreElement.textContent = score;
                    
                    // 更新最高分
                    if (score > highScore) {
                        highScore = score;
                        highScoreElement.textContent = highScore;
                        localStorage.setItem('snakeHighScore', highScore);
                    }
                    
                    // 增加速度
                    currentSpeed = Math.max(50, currentSpeed * (1 - speedIncrease));
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, currentSpeed);
                    
                    // 生成新食物
                    generateFood();
                    
                    // 标记已吃到食物
                    foodEaten = true;
                }
            }
            
            // 游戏结束处理
            function gameOver() {
                isGameOver = true;
                clearInterval(gameInterval);
                
                // 显示游戏结束界面
                gameOverElement.style.display = 'block';
                finalScoreElement.textContent = score;
                
                // 显示分数比较
                if (score > highScore) {
                    scoreComparisonElement.textContent = '新纪录!';
                } else if (score === highScore) {
                    scoreComparisonElement.textContent = '平了最高分!';
                } else {
                    scoreComparisonElement.textContent = `距离最高分还差 ${highScore - score} 分`;
                }
            }
            
            // 绘制游戏
            function drawGame() {
                // 清空画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制网格线
                drawGrid();
                
                // 绘制蛇
                drawSnake();
                
                // 绘制食物
                drawFood();
            }
            
            // 绘制网格线
            function drawGrid() {
                ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)';
                ctx.lineWidth = 1;
                
                // 垂直线
                for (let x = 0; x <= config.gridSize; x++) {
                    ctx.beginPath();
                    ctx.moveTo(x * config.cellSize, 0);
                    ctx.lineTo(x * config.cellSize, canvas.height);
                    ctx.stroke();
                }
                
                // 水平线
                for (let y = 0; y <= config.gridSize; y++) {
                    ctx.beginPath();
                    ctx.moveTo(0, y * config.cellSize);
                    ctx.lineTo(canvas.width, y * config.cellSize);
                    ctx.stroke();
                }
            }
            
            // 绘制蛇
            function drawSnake() {
                // 绘制蛇身
                for (let i = 0; i < snake.length; i++) {
                    const segment = snake[i];
                    
                    // 计算颜色渐变
                    const hue = 120; // 绿色
                    const saturation = 100;
                    const lightness = 50 - (i / snake.length * 30);
                    
                    ctx.fillStyle = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
                    ctx.fillRect(
                        segment.x * config.cellSize,
                        segment.y * config.cellSize,
                        config.cellSize,
                        config.cellSize
                    );
                    
                    // 绘制边框
                    ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
                    ctx.strokeRect(
                        segment.x * config.cellSize,
                        segment.y * config.cellSize,
                        config.cellSize,
                        config.cellSize
                    );
                }
                
                // 绘制蛇眼（头部）
                const head = snake[0];
                const eyeSize = config.cellSize / 5;
                const eyeOffset = config.cellSize / 3;
                
                // 根据方向确定眼睛位置
                let leftEyeX, leftEyeY, rightEyeX, rightEyeY;
                
                switch(direction) {
                    case 'up':
                        leftEyeX = head.x * config.cellSize + eyeOffset;
                        leftEyeY = head.y * config.cellSize + eyeOffset;
                        rightEyeX = head.x * config.cellSize + config.cellSize - eyeOffset;
                        rightEyeY = head.y * config.cellSize + eyeOffset;
                        break;
                    case 'down':
                        leftEyeX = head.x * config.cellSize + eyeOffset;
                        leftEyeY = head.y * config.cellSize + config.cellSize - eyeOffset;
                        rightEyeX = head.x * config.cellSize + config.cellSize - eyeOffset;
                        rightEyeY = head.y * config.cellSize + config.cellSize - eyeOffset;
                        break;
                    case 'left':
                        leftEyeX = head.x * config.cellSize + eyeOffset;
                        leftEyeY = head.y * config.cellSize + eyeOffset;
                        rightEyeX = head.x * config.cellSize + eyeOffset;
                        rightEyeY = head.y * config.cellSize + config.cellSize - eyeOffset;
                        break;
                    case 'right':
                        leftEyeX = head.x * config.cellSize + config.cellSize - eyeOffset;
                        leftEyeY = head.y * config.cellSize + eyeOffset;
                        rightEyeX = head.x * config.cellSize + config.cellSize - eyeOffset;
                        rightEyeY = head.y * config.cellSize + config.cellSize - eyeOffset;
                        break;
                }
                
                // 绘制眼睛
                ctx.fillStyle = 'white';
                ctx.beginPath();
                ctx.arc(leftEyeX, leftEyeY, eyeSize, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.beginPath();
                ctx.arc(rightEyeX, rightEyeY, eyeSize, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制瞳孔
                ctx.fillStyle = 'black';
                ctx.beginPath();
                ctx.arc(leftEyeX, leftEyeY, eyeSize / 2, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.beginPath();
                ctx.arc(rightEyeX, rightEyeY, eyeSize / 2, 0, Math.PI * 2);
                ctx.fill();
            }
            
            // 绘制食物
            function drawFood() {
                const centerX = food.x * config.cellSize + config.cellSize / 2;
                const centerY = food.y * config.cellSize + config.cellSize / 2;
                const radius = config.cellSize / 2 - 2;
                
                // 绘制红色圆形食物
                ctx.fillStyle = '#e74c3c';
                ctx.beginPath();
                ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
                ctx.fill();
                
                // 添加高光效果
                ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
                ctx.beginPath();
                ctx.arc(
                    centerX - radius / 3,
                    centerY - radius / 3,
                    radius / 4,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
            }
            
            // 键盘控制
            document.addEventListener('keydown', (e) => {
                // 如果游戏暂停
                if (isPaused || isGameOver) {
                    if (e.code === 'Space') {
                        togglePause();
                    }
                    return;
                }
                
                switch(e.code) {
                    case 'ArrowUp':
                        if (direction !== 'down') nextDirection = 'up';
                        break;
                    case 'ArrowDown':
                        if (direction !== 'up') nextDirection = 'down';
                        break;
                    case 'ArrowLeft':
                        if (direction !== 'right') nextDirection = 'left';
                        break;
                    case 'ArrowRight':
                        if (direction !== 'left') nextDirection = 'right';
                        break;
                    case 'Space':
                        togglePause();
                        break;
                }
            });
            
            // 触摸控制（简化版，实际项目中需要更复杂的触摸检测）
            let touchStartX = 0;
            let touchStartY = 0;
            
            canvas.addEventListener('touchstart', (e) => {
                e.preventDefault();
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
            });
            
            canvas.addEventListener('touchend', (e) => {
                e.preventDefault();
                const touchEndX = e.changedTouches[0].clientX;
                const touchEndY = e.changedTouches[0].clientY;
                
                const dx = touchEndX - touchStartX;
                const dy = touchEndY - touchStartY;
                
                // 如果游戏暂停或结束，点击中央区域可以暂停/继续
                if (Math.abs(dx) < 10 && Math.abs(dy) < 10) {
                    togglePause();
                    return;
                }
                
                // 确定滑动方向
                if (Math.abs(dx) > Math.abs(dy)) {
                    // 水平滑动
                    if (dx > 0 && direction !== 'left') {
                        nextDirection = 'right';
                    } else if (dx < 0 && direction !== 'right') {
                        nextDirection = 'left';
                    }
                } else {
                    // 垂直滑动
                    if (dy > 0 && direction !== 'up') {
                        nextDirection = 'down';
                    } else if (dy < 0 && direction !== 'down') {
                        nextDirection = 'up';
                    }
                }
            });
            
            // 暂停/继续游戏
            function togglePause() {
                if (isGameOver) return;
                
                isPaused = !isPaused;
                
                if (isPaused) {
                    clearInterval(gameInterval);
                    pauseButton.textContent = '继续';
                } else {
                    gameInterval = setInterval(gameLoop, currentSpeed);
                    pauseButton.textContent = '暂停';
                }
            }
            
            // 按钮事件监听
            startButton.addEventListener('click', () => {
                if (!gameInterval && !isGameOver) {
                    initGame();
                    gameInterval = setInterval(gameLoop, currentSpeed);
                    startButton.disabled = true;
                    pauseButton.disabled = false;
                }
            });
            
            pauseButton.addEventListener('click', togglePause);
            
            // 修正这里：修复语法错误
            resetButton.addEventListener('click', () => {
                clearInterval(gameInterval);
                initGame();
                startButton.disabled = false;
                pauseButton.disabled = true;
                pauseButton.textContent = '暂停';
                isPaused = false;
            });
            
            restartButton.addEventListener('click', () => {
                gameOverElement.style.display = 'none';
                initGame();
                gameInterval = setInterval(gameLoop, currentSpeed);
                startButton.disabled = true;
                pauseButton.disabled = false;
            });
            
            difficultySelector.addEventListener('change', updateDifficulty);
            
            // 初始化最高分显示
            highScoreElement.textContent = highScore;
            
            // 初始绘制
            initGame();
        });
    </script>
</body>
</html>